'use strict';

const Service = require('egg').Service;
class UsersService extends Service {
  async login(username, password) {
    const user = await this.ctx.model.Users.findOne({ username: username })
    if (user) {
      if (user.password == password) {
        const token = await this.app.jwt.sign({
          username: this.ctx.request.body.username
        }, this.config.jwt.secret)
        this.ctx.body = token
        await this.ctx.model.Users.updateOne({
          username: username
        }, {
          token: token
        })
        this.ctx.response.body = {
          code: 200,
          msg: '登陆成功',
          result: {
            token: token
          },
        }
      } else {
        this.ctx.response.body = {
          code: 'error',
          msg: '密码错误!',
          data: {}
        }
      }
    } else {
      this.ctx.response.body = {
        code: 'error',
        msg: '用户不存在!',
        data: {}
      }
    }
  }
  async info() {
    const token = this.ctx.request.header.authorization.split(' ')[1];
    const user = await this.ctx.model.Users.findOne({ token })
    this.ctx.response.body = {
      code: 200,
      msg: "获取用户信息成功",
      result: {
        "avatar": user.info.avator,
        "status": user.info.status,
        "lastLoginIp": user.info.creatorId,
        "createTime": user.info.createdAt,
        "deleted": user.info.deleted,
        "role": {
          "id": user.info.role.id,
          "username": user.info.role.name,
          "status": user.info.role.status,
          "actionList": user.info.role.actionList,
          "deleted": user.info.role.deleted,
          "permissions": [user.info.role.permissions[0]]
        }
      }
    }

  }
  async nav() {
    const token = this.ctx.request.headers.authorization.split(' ')[1];
    const user = await this.ctx.model.Users.findOne({ token });
    user.menu = []
    const len = user.info.menuList.length
    for (let i = 0; i < len; i++) {
      const menu = await this.ctx.model.Users.findOne({ name: user.info.menuList[i] });
      user.menu[i] = menu;
    }
    this.ctx.response.body = {
      code: 200,
      message: "获取用户菜单成功",
      result: user.menu
    };

  }
}

module.exports = UsersService;
